package com.nian.common.lock.redis;

import com.nian.common.model.ServerResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * 用途：
 * 开发：zhangmj
 * 日期：2020/4/13 0013 18:08
 */
@Slf4j
@RestController
@RequestMapping("testRedisLock")
public class TestRedisLock {

    public static final String LOCK_NAME = "redis_distributed_lock_test";


//    @Qualifier("redisDistributedUpgradeLock")
//    @Qualifier("redisDistributedLuaLock")

    @Qualifier("redisDistributedBaseLock")
    @Autowired
    IRedisLock iRedisLock;

    @PostMapping("tryLock")
    public ServerResponse tryLock(){
        try{
            String requestId = UUID.randomUUID().toString();
            int count = 1;
            while (true && count < 11){
                Boolean rs = iRedisLock.lock(LOCK_NAME, requestId, 10*1000);
                log.info("ThreadName:{} requestId:{} 第 {} 次 获取分布式锁结果:{}", Thread.currentThread().getName(), requestId, count, rs);
                if(rs){
                    Thread.sleep(6*1000);
                    iRedisLock.unLock(LOCK_NAME, requestId);
                    return ServerResponse.createBySuccessMessage("第 " + count + " 次 获取锁成功");
                }
                count ++;
                Thread.sleep(1*1000);
            }
            return ServerResponse.createByErrorMessage("在60秒内,10次获取锁失败");
        }catch (Exception e){
            log.error("redis 分布式锁处理错误:", e);
        }
        return ServerResponse.createByError();
    }
}
